package OldInfo

import "strconv"
import (
	"Shares/Model"
	"io/ioutil"
	"encoding/json"
	"fmt"
	"net/http"
	"log"
	"github.com/jinzhu/gorm"
	_"github.com/go-sql-driver/mysql"
)

const Appid="756223fa3923f8789937cb0b0f4b9634"
var(
	code="&code=600418"
	index="&index=false"
	k_type="&k_type=day"
	fq_type="&fq_type=qfq"
	start_date="&start_date=2017-01-01"
	end_date="&end_date=2018-04-04"
)

type IndexInfo struct {
	Date string`json:"date"`
	Open string`json:"open"`
	Close string`json:"close"`
	High string`json:"high"`
	Low string`json:"low"`
	Volume string`json:"volume"`
	Code string`json:"code"`
}

//type SharesOldInfo struct {
//	Id uint
//	Code int
//	Date string
//	Open float64
//	Close float64
//	High float64
//	Low float64
//	Volume float64
//}

type oldInfoSrc struct {
	ErrorCode int `json:"error_code"`
	Data []IndexInfo`json:"data"`
	//Data []struct{
	//	Date string`json:"date"`
	//	Open string`json:"open"`
	//	Close string`json:"close"`
	//	High string`json:"high"`
	//	Low string`json:"low"`
	//	Volume string`json:"volume"`
	//	Code string`json:"code"`
	//}
	Reason string `json:"reason"`
}


type History struct {
	src oldInfoSrc
	des []Model.SharesOldInfo
}

func(self*History)GetInfo(){
	res,err:=http.Get("http://api.shenjian.io/?appid="+Appid+code+index+k_type+fq_type+start_date+end_date)
	if err!=nil{
		log.Fatal(err)
	}
	data,err:=ioutil.ReadAll(res.Body)
	err=json.Unmarshal(data,&self.src)
	if err!=nil{
		log.Fatal(err)
	}
}

func(this*History)Trans(){
	var res =new(Model.SharesOldInfo)
	for _,self:=range this.src.Data{
		code:=self.Code[2:]
		res.Code,_=strconv.Atoi(code)
		res.Open,_=strconv.ParseFloat(self.Open,64)
		res.Close,_=strconv.ParseFloat(self.Close,64)
		res.High,_=strconv.ParseFloat(self.High,64)
		res.Low,_=strconv.ParseFloat(self.Low,64)
		res.Volume,_=strconv.ParseFloat(self.Volume,64)
		res.Date=self.Date
		fmt.Printf("%+v\n",*res)
		this.des=append(this.des,*res)
	}
}

func(self*History)Save(){
	db, err := gorm.Open("mysql", "root:cxx15755599659@/Ticket?charset=utf8&parseTime=True&loc=Local")

	if err != nil {
		panic("failed to connect database")
	}
	defer db.Close()
	db.AutoMigrate(&Model.SharesOldInfo{})
	for _,elem:=range self.des{
		db.Create(&elem)
		fmt.Printf("%+v\n",elem)
	}

}

func(self*History) Start(){
	self.GetInfo()
	self.Trans()
	self.Save()
}